import router from '@/router'
import apiUser from '@/api/modules/user'

interface UserState {
  id?: number
  username: string
  token: string
  permissions: string[]
}

const useUserStore = defineStore(
  // 唯一ID
  'sztu.meeting.user',
  {
    state: (): UserState => ({
      id: undefined,
      username: '',
      token: '',
      permissions: [],
    }),
    getters: {
      isLogin: (state: UserState) => {
        return !!state.token
      },
    },
    actions: {
      // 登录
      async login(data: LoginBody) {
        this.$reset()
        return apiUser.login(data)
          .then((res) => {
            this.id = res.data.admin.id
            this.username = res.data.admin.username
            this.token = res.data.token
            this.permissions = []
            return res
          })
      },

      // 登出
      async logout() {
        apiUser.logout()
        this.$reset()
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.value.path !== '/login' ? router.currentRoute.value.fullPath : undefined,
          },
        })
      },

      // 获取我的权限
      async getPermissions() {
        return this.permissions
      },

      // 修改密码
      async editPassword(data: { oldPassword: string; newPassword: string }) {
        return apiUser.passwordEdit({
          id: this.id!,
          oldPwd: data.oldPassword,
          newPwd: data.newPassword,
        })
      },
    },
    persist: {
      enabled: true,
    },
  },
)

export default useUserStore
